package com.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.food.entity.dto.MerchantLoginDto;
import com.food.entity.pojo.Merchant;
import com.food.entity.vo.MerchantRegisterVo;
import com.food.mapper.MerchantMapper;
import com.food.service.MerchantService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-03
 */
@Service
public class MerchantServiceImpl extends ServiceImpl<MerchantMapper, Merchant> implements MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    public Merchant login(MerchantLoginDto merchantLoginDto) {
        LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchant::getPhone, merchantLoginDto.getPhone());
        Merchant merchant = merchantMapper.selectOne(queryWrapper);

        if (merchant == null) {
            // 用户不存在，抛出异常或返回 null，并记录日志
            // 可以选择抛出自定义异常，或者由 Controller 层统一处理
            throw new RuntimeException("用户不存在");
        }

        if (!merchant.getPassword().equals(merchantLoginDto.getPassword())) {
            // 密码错误
            throw new RuntimeException("密码错误");
        }

        return merchant;
    }


    @Override
    public void register(MerchantRegisterVo merchantRegisterVo) {
        LambdaQueryWrapper<Merchant> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Merchant::getPhone, merchantRegisterVo.getPhone());
        if(merchantMapper.selectOne(queryWrapper) != null){
            //todo: 用户已存在
        }
        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(merchantRegisterVo, merchant);
        int insert = merchantMapper.insert(merchant);
        if(insert < 0){
            //todo: 注册失败
        }
    }

    @Override
    public void updateMerchant(Merchant merchant) {
        int i = merchantMapper.updateById(merchant);
        if(i < 0){
            //todo: 更新失败
        }
    }

    @Override
    public void deleteMerchant(Integer id) {
        int i = merchantMapper.deleteById(id);
        if(i < 0){
            //todo: 删除失败
        }
    }
}
